package net.starwifi.duobao.web;

import net.starwifi.duobao.entity.Operator;
import net.starwifi.duobao.mvc.Message;
import net.starwifi.duobao.service.OperatorService;
import net.starwifi.duobao.utils.StringUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 用户面板
 * Created by ruo on 2015/4/7.
 */
@Controller("adminProfileController")
@RequestMapping("/profile")
public class ProfileController extends BaseController {

    @Autowired
    OperatorService operatorService;


    /**
     * 编辑
     */
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public String info(ModelMap model) {
        model.addAttribute("entity", operatorService.getCurrent());
        return "/profile/info";
    }

    /**
     * 编辑
     */
    @RequestMapping(value = "/pass", method = RequestMethod.GET)
    public String changePass() {
        return "/profile/pass";
    }

    /**
     * 编辑
     */
    @RequestMapping(value = "/pass", method = RequestMethod.POST)
    public String changePass(String originalPass,String pass,String passTwo, RedirectAttributes redirectAttributes) {
        if(originalPass==null||pass==null||passTwo==null){
            addFlashMessage(redirectAttributes, Message.error("参数不能为空"));
            return "redirect:pass";
        }
        if(!isValid(Operator.class,"password",originalPass)||!isValid(Operator.class,"password",originalPass)){
            addFlashMessage(redirectAttributes, Message.error("参数填写有误"));
            return "redirect:pass";
        }
        if(!pass.equals(passTwo)){
            addFlashMessage(redirectAttributes, Message.error("两次输入密码不一致"));
            return "redirect:pass";
        }
        Operator operator=operatorService.getCurrent();
        if(operator==null){
            addFlashMessage(redirectAttributes, Message.error("管理员信息有误"));
            return "redirect:pass";
        }
        if (!DigestUtils.md5Hex(originalPass + operator.getSalt()).equals(operator.getPassword())) {
            addFlashMessage(redirectAttributes, Message.error("原始密码不正确"));
            return "redirect:pass";
        }
        String newSalt= StringUtils.getUUID();
        String newPass=DigestUtils.md5Hex(pass + newSalt);
        operator.setSalt(newSalt);
        operator.setPassword(newPass);
        operatorService.update(operator);
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:pass";

    }




}
